package com.zte.cl.listener;

import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.zte.cl.model.News;
import com.zte.cl.parser.PageTemplateUtil;
import com.zte.cl.repository.NewsRepository;
import com.zte.cl.service.NewsQueue;
import com.zte.cl.utils.ConstantUtil;
import com.zte.cl.utils.DateUtil;

public class MyServletContextListener implements ServletContextListener {

	private static Log log = LogFactory.getLog(MyServletContextListener.class);

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		log.debug("爬虫服务关闭======================");
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		log.debug("爬虫服务启动======================");
		
		// 初始化常量
		ConstantUtil.getInstance();
		
		// 初始化模板
		PageTemplateUtil.load();
		
		ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(arg0.getServletContext()); 
		
		// 系统重新启动后，NewsQueue初始化
		log.info("初始化NewsQueue.....");
		NewsRepository newsRepository = (NewsRepository)ac.getBean("newsRepository");
		List<News> newsList = newsRepository.findByIsEnabledFalseAndInsertTimeGreaterThan(DateUtil.parseDate(DateUtil.C_DATE_PATTON_DEFAULT, DateUtil.getCurrentDateStr()));
		log.info("NewsQueue初始化完毕.....");
		if(newsList != null && newsList.size() > 0) {
			for(News news : newsList) {
				NewsQueue.push(news);
			}
		}
	}
	
}
